package org.gjy.m8.stream;

import com.google.common.collect.Lists;
import org.gjy.m8.stream.collect.StudentCollect;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-11-04 10:39:45
 */
public class Collector2Test {

    @Test
    public void test1() {
        ArrayList<Student> students = Lists.newArrayList(
                new Student(18, "gjy"),
                new Student(19, "qq"),
                new Student(18, "yq"),
                new Student(19, "pp"),
                new Student(28, "acc"),
                new Student(28, "ppq")
        );
        Map<Integer, Student> collect = students.stream()
                .collect(Collectors.toMap(Student::getAge, s -> s, (l, f) -> {
                    l.setName(l.getName() + "," + f.getName());
                    return l; // 合并重复key的value
                }));
        System.out.println(collect);
    }

    @Test
    public void test2() {
        ArrayList<Student> students = Lists.newArrayList(
                new Student(18, "gjy"),
                new Student(19, "qq"),
                new Student(18, "yq"),
                new Student(19, "pp"),
                new Student(28, "acc"),
                new Student(28, "ppq")
        );
        Map<Integer, List<Student>> collect = students.stream().collect(new StudentCollect());
        collect.forEach((k, v) -> System.out.println(k + ": " + v));

        /*students.stream()
                .collect(new StudentCollect());*/
    }

    @Test
    public void test3() {
        HashMap<String, List<Integer>> map = new HashMap<>();
        map.put("a", Lists.newArrayList(1, 2, 3));
        map.computeIfAbsent("a", k -> new ArrayList<>()).add(1);
        System.out.println(map);
    }

    @Test
    public void test4() {
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(1, 1);
        map.putIfAbsent(1, 10);
        System.out.println(map);
    }

    @Test
    public void test5() {
        Dish dish = new Dish();
        dish.setName("dd");
        dish.setVegetarian(false);
        Student student = new Student(18, "gjy", dish);
        Student s2 = student.clone();

        System.out.println("student = " + student);
        System.out.println("s2 = " + s2);

        s2.setName("qq");
        s2.setAge(22);
        dish.setName("fff");
        s2.setDish(dish);
        System.out.println("student = " + student);
        System.out.println("s2 = " + s2);
    }

}
